package com.vstudy.zx.service.impl;

import com.vstudy.zx.dao.ConversationDao;
import com.vstudy.zx.dao.MessageDao;
import com.vstudy.zx.dao.StudentDao;
import com.vstudy.zx.dao.TeacherDao;
import com.vstudy.zx.entity.Conversation;
import com.vstudy.zx.entity.Message;
import com.vstudy.zx.entity.Student;
import com.vstudy.zx.entity.Teacher;
import com.vstudy.zx.service.MessageService;
import com.vstudy.zx.utils.models.MessageModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public class MessageServiceImpl implements MessageService {
    @Autowired
    private ConversationDao conversationDao;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private TeacherDao teacherDao;
    @Autowired
    private StudentDao studentDao;

    @Override
    public List<MessageModel> getMessageByCon(Long conId) {
        Conversation c = conversationDao.selectById(conId);
        Teacher teacher = teacherDao.selectById(c.getTe_id());
        Student student = studentDao.selectById(c.getStu_id());

        List<Message> messages = messageDao.selectMessage(conId, 10);
        List<MessageModel> msgModels = new ArrayList<>();
        for (Message msg : messages) {
            MessageModel m = new MessageModel();
            m.setMsgTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(msg.getMsg_time()));
            m.setText(msg.getMsg_message());

            //头像
            if (msg.getFrom_id() == 1) { // 教师方发送的
                m.setImage(teacher.getTe_image());
                m.setDir("right");
            } else {
                m.setImage(student.getStu_image());
                m.setDir("left");
            }
            msgModels.add(m);
        }
        return msgModels;
    }

    @Override
    public int saveMsg(Long conId, String msg) {
        // fromId=1, 时间使用mysql默认值
        // 修改学生端状态
        conversationDao.updateStuStatus(conId, false);
        int rs = messageDao.add(conId, msg, 1);
        return rs;
    }
}
